package com.sac.system.shiro;

import com.sac.common.config.ApplicationContextRegister;
import com.sac.common.utils.ShiroUtils;
import com.sac.system.dao.UserDao;
import com.sac.system.domain.UserDO;
import com.sac.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Long userId = Long.parseLong(ShiroUtils.getEmpId());
		MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String empId = (String) token.getPrincipal();
		Map<String, Object> map = new HashMap<>(16);
		map.put("empId", empId);
		String password = new String((char[]) token.getCredentials());

		UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
		// 查询用户信息
		UserDO user = userMapper.list(map).get(0);

		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
//		if (!password.equals(user.getPassword())) {
//			throw new IncorrectCredentialsException("账号或密码不正确");
//		}

		// 账号锁定
		if (user.getStatusCode().equals("D")){
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getEmpId(), password, getName());
		SecurityUtils.getSubject().getSession().setAttribute("currentUser",user);
		return info;
	}

}
